package com.mysounds;

import java.util.HashMap;

import lt.startup.duobes.R;

import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
import android.view.View;


public class SoundThread extends Thread{
	public static final int BEEP = 1;
	private SoundPool soundPool;
	private HashMap<Integer, Integer> soundPoolMap;

	private View mView;
    public boolean mRun = false;
    public boolean soundCycle = false;
    public int soundInt = 1000;
    public float soundFreq = 1;
    
    public SoundThread(View panel) {
    	mView = panel;
        initSounds();
    }
    
    public void setRunning(boolean run) {
        mRun = run;
    }
    
    @Override
    public void run() {
        while (mRun) {
        	try{
        	    while(soundCycle){
        	    	if(soundFreq != -1f){
//        	    		Log.v("Sound options", "Running beep");
	        	    	playSound(BEEP, 1);
	    	    		Thread.sleep(200);
        	    	}
        	    }
        	} catch(InterruptedException e){
//	    		Log.v("Sound options", "Stopping beep");
//        		soundCycle = false;
//        		soundPool.stop(BEEP);
        	}
        }
    }
	@SuppressWarnings("unused")
	private void initSounds() {
	     soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
	     soundPoolMap = new HashMap<Integer, Integer>();
	     soundPoolMap.put(BEEP, soundPool.load(mView.getContext(), R.raw.beep, 1));
	}
	          
	public void playSound(int sound, float freq) {
		/* Updated: The next 4 lines calculate the current volume in a scale of 0.0 to 1.0 */
	    AudioManager mgr = (AudioManager)mView.getContext().getSystemService(mView.getContext().AUDIO_SERVICE);
	    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
	    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
	    float volume = streamVolumeCurrent / streamVolumeMax;
	    
	    /* Play the sound with the correct volume */
		soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, freq);

	}
	public void stopSound(int sound){
		soundPool.stop(soundPoolMap.get(sound));
	}
	
}
